/*
 * Copyright (C) 2022 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package cn.kcrx.autoweightapp.fragment.viewmodes

import android.content.Context
import android.os.Environment
import android.view.View
import androidx.lifecycle.*
import cn.kcrx.autoweightapp.data.NewCashBoxRecord
import cn.kcrx.autoweightapp.data.NewCashBoxRepository
import cn.kcrx.autoweightapp.utils.ExcelUtil
import cn.kcrx.autoweightapp.utils.XToastUtils
import com.xuexiang.xutil.data.DateUtils
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import mu.KotlinLogging
import java.io.File
import java.util.*
import javax.inject.Inject

@HiltViewModel
class FragmentQueryViewModel @Inject internal constructor(
    private val newCashBoxRepository: NewCashBoxRepository
):ViewModel() {
     val logger=KotlinLogging.logger(this.javaClass.simpleName)

    private  val _records=MutableLiveData<List<NewCashBoxRecord>>(mutableListOf())
    val record:LiveData<List<NewCashBoxRecord>>
    get() = _records


    fun getTodayDate(from:Date,to:Date){
        val fromcl=Calendar.getInstance()
        fromcl.time=from
        fromcl.set(Calendar.HOUR_OF_DAY,0)
        fromcl.set(Calendar.MINUTE,0)
        fromcl.set(Calendar.SECOND,0)
        val tocl=Calendar.getInstance()
        tocl.time=to
        viewModelScope.launch {
          val rs=withContext(Dispatchers.IO){
               newCashBoxRepository.getTodayRecords(fromcl,tocl)
           }
            _records.value=rs
        }
    }

    fun exportExcel(context:Context){
        try {
            val excelPath= "/sdcard/kcrx/records"
            val exclePathFile= File(excelPath)
            if(!exclePathFile.exists()){
                exclePathFile.mkdirs()
            }
            val excelFileName=DateUtils.date2String(Date(),DateUtils.yyyyMMdd.get())+".xls"
            val titles= arrayOf("id","券别","重量","日期")
            val sheetname="称重记录表"
            val excelFile=File("$excelPath${File.separator}$excelFileName")
            ExcelUtil.initExcel(excelFile.path,sheetname,titles)
            ExcelUtil.writeObjListToExcel(record.value,excelFile.path,context)
            logger.error { "称重记录导出成功！！数量=${record.value!!.size}" }
            XToastUtils.success( "称重记录导出成功！！数量=${record.value!!.size}")
        }catch (e:Exception){
            logger.error(e) {"称重记录导出失败!"  }
            XToastUtils.error( "称重记录导出失败!")
        }

    }

}